package com.example.study.page.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.study.databinding.FragmentPagingBinding
import com.example.study.page.adapter.CustomPagingDataAdapter
import com.example.study.source.CustomPagingSource
import com.example.study.source.MovieRepository
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch


class PagingFragment : Fragment() {
    private lateinit var binding: FragmentPagingBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentPagingBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val moviePager =
            Pager(PagingConfig(pageSize = 10, prefetchDistance = 3), pagingSourceFactory = {
                CustomPagingSource(
                    MovieRepository()
                )
            }).flow
        binding.recyclerview.apply {
            layoutManager = LinearLayoutManager(context).apply {
                orientation = LinearLayoutManager.VERTICAL
            }
        }
        val adapter = CustomPagingDataAdapter()
        binding.recyclerview.adapter = adapter
        adapter.refresh()
        lifecycleScope.launch {
            moviePager.collectLatest {
                adapter.submitData(it)
            }
        }

    }
}